<template>
  <div>
    <count :init="4" @change="changeHandler" @fatherChange="fatherChangeHandler" ref="countComponent" style="color:red;">
      <h1>后盾人</h1>
      <h2>学好vue</h2>
    </count>
    <br>
    {{count}}
    <br>
    {{ fatherChangeHandler() }}
  </div>
</template>

<script>
  import Count from './components/Count.vue'
  import {ref,onMounted,onBeforeMount,onBeforeUpdate,onUpdated,onBeforeUnmount,onUnmounted,provide} from 'vue'
  export default {
    components:{Count},
    // setup相当于create生命周期，所以setup中没有beforeCreate和created生命周期
    setup(){
      let count = ref(0);
      const changeHandler = (val) => {
        count.value = val;
      };

      //父组件直接读取子组件的数据和方法,并且要把countComponent返回出去
      const countComponent = ref();
      //必须等到挂载结束，才能读取到元素
      onMounted(() => {
        console.log(countComponent.value.num);
        console.log(countComponent.value.add);  //子组件没有暴露add方法，所以读取不到add方法
      });

      const fatherChangeHandler = () => {
         return countComponent.value ? countComponent.value.num : '';
      };

      let user = ref("数据穿透-父组件改变之前");
      setTimeout(() => user.value = "数据穿透-父组件改变之后",1000);
      provide('user',user);
      provide('updateUser',newValue => user.value = newValue);

      return {count,changeHandler,countComponent,fatherChangeHandler};
    }
  }
</script>

<style lang="scss" scoped>

</style>
